//
//  WHTFirstPageControllerVC.m
//  WZLProduct
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 HaiTeng. All rights reserved.
//

#import "WHTFirstPageControllerVC.h"
#import "FistPageCollectionHeaderView_Ht.h"
#import "HTLBView.h"
#import "firstPageFirstSecctionCell_Ht.h"
#import "firstPageSecondSecctionCell_Ht.h"
#import "FirstPageFirstModel_Ht.h"
#import "WHTFirstPageTripModel.h"
#import "FirstPageSearchPage_Ht.h"
#import "WHTWKWebViewVC.h"
#import "WHTStroryVC.h"
#import "WHTStroryDetailVC.h"

@interface WHTFirstPageControllerVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,HTLBDelegate,UITextFieldDelegate,FirstPageSearchPage_HtDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, retain) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) FirstPageFirstModel_Ht *model;
@property (nonatomic, strong) HTLBView *lbView; /**< 轮播图 */
@property (nonatomic, assign) NSInteger nextPage; /**< 下一页 */
@property (nonatomic, strong) FirstPageSearchPage_Ht *searchPage; /**< 搜索页 */
@property (nonatomic, strong) UITextField *textField; /**< 搜索框 */

@end



@implementation WHTFirstPageControllerVC

static NSString *firstPageFirstSecctionCell_id_Ht = @"firstPageFirstSecctionCell_id_Ht";
static NSString *firstPageSecondSecctionCell_id_Ht = @"firstPageSecondSecctionCell_id_Ht";
static NSString *fistPageCollectionHeaderIdentifier = @"fistPageCollectionHeaderIdentifier";



- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
         self.model = [[FirstPageFirstModel_Ht alloc] init];
        [self requestDataByURL:KUrl_FistPage_WHT];
        self.view.backgroundColor = [UIColor colorWithRed:0.91 green:0.87 blue:0.78 alpha:1];
        [self setNavigationBar];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatCollectionView];
    [self lbData];
    [self addFooter];
    [self setSearchPage];
    
}

#pragma mark- 请求数据

#pragma mark 上拉加载更多
- (void)addFooter
{
    __weak WHTFirstPageControllerVC *tempVC = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        [tempVC requestMoreData];
    }];
    
    [footer setTitle:@"BAT_Click or drag up to refresh" forState:MJRefreshStateIdle];
    [footer setTitle:@"BAT_Loading more ..." forState:MJRefreshStateRefreshing];
    [footer setTitle:@"BAT_No more data" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.textColor = kAppearanceColor;
    self.collectionView.mj_footer = footer;
    
}


- (void)requestMoreData{

    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/index/?lat=38.88267820468585&lng=121.5392831248391&next_start=%@&sign=3f4c6287431178620edad37b88e6f36e",self.model.next_start];
     __weak WHTFirstPageControllerVC *tempVC = self;
    
    [RequestData creatingDataTask:str parameters:nil Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
        [tempVC setModelAndReloadUIByData:resuposeObject];
        [tempVC.collectionView.mj_footer endRefreshing];
    }];
    
                /*
                 拿到当前的上拉刷新控件，变为没有更多数据的状态
                 if (没找到数据里的判断点,正常数据里是会有判断点的例如:maxPage ) {
                 [tempVC.collectionView.mj_footer endRefreshingWithNoMoreData];
                 }
                 */
}

- (void)requestDataByURL:(NSString *)url{

    __weak WHTFirstPageControllerVC *tempVC = self;
    [self MMHUDRunning];
        [RequestData GETRequestWithURLString:url completionWithSuccess:^(id result) {
            [tempVC setModelAndReloadUIByData:result];
            //成功了菊花隐藏
                [MMProgressHUD dismissWithSuccess:@"旅行!"];
        } WithFailure:^(id error) {
            [tempVC setModelAndReloadUIByData:error];
            //成功了菊花隐藏
                [MMProgressHUD dismissWithSuccess:@"旅行!"];
                    }];


}
- (void)setModelAndReloadUIByData:(id)data{
  __weak WHTFirstPageControllerVC *tempVC = self;
    [tempVC.model setValuesForKeysWithDictionary:data[@"data"]];
    //刷新UI
    [tempVC.collectionView reloadData];
   
}
#pragma mark 轮播图数据
- (void)lbData{
    
    //找到存数据的路径,判断本地是否有数据,若有,直接取
    __weak WHTFirstPageControllerVC *tempVC = self;
        [RequestData GETRequestWithURLString:KUrl_FistPage_WHT completionWithSuccess:^(id result) {
            [tempVC setLbData:result];
        } WithFailure:^(id error) {
            [tempVC setLbData:error];
        }];

}
- (void)setLbData:(id)data{
    NSMutableArray *dataArray = data[@"data"][@"elements"];
    NSMutableArray *tempArray = dataArray.firstObject[@"data"];
    NSMutableArray *lbImgArray = [NSMutableArray array];
    NSMutableArray *htmlArray = [NSMutableArray array];
    for (NSDictionary *dic in tempArray.firstObject) {
        [lbImgArray addObject:dic[@"image_url"]];
        [htmlArray addObject:dic[@"html_url"]];
    }
    //Block 回调, 传轮播图图片数据
    self.lbView.htLBdelegate = self;
    self.lbView.dataArrayHtml = [NSMutableArray arrayWithArray:htmlArray];
    self.lbView.sendScrollImageDataArray(lbImgArray);


   
}


#pragma mark- 设置导航栏
- (void)setNavigationBar{
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"HT_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back:)]];

    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 20, kScreenWidth - 100, 30)];
    self.navigationItem.titleView = _textField;
    _textField.placeholder = @"🔍搜索目的地.游记....";
    _textField.textAlignment = NSTextAlignmentCenter;
    _textField.textColor = [UIColor orangeColor];
    _textField.delegate = self;
    
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"附近" style:UIBarButtonItemStylePlain target:self action:@selector(RightBarButtonAction:)]];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor orangeColor];

    
}
#pragma mark 返回
- (void)back:(UIBarButtonItem *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 附近
- (void)RightBarButtonAction:(UIBarButtonItem *)sender{

    if ([sender.title isEqualToString:@"取消"]) {
        [self.textField resignFirstResponder];
        
        [UIView animateWithDuration:0.3 animations:^{
            self.searchPage.frame = CGRectMake(0, 0, kScreenWidth, 0.01);
        }];
      
    }else{
        //附近
    }
}


#pragma mark- CollectionView
- (void)creatCollectionView{
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) collectionViewLayout:_layout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:0.91 green:0.87 blue:0.78 alpha:1];
    self.collectionView.contentInset = UIEdgeInsetsMake(200, 0, 0, 0);


    
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    //注册
    [self.collectionView registerClass:[firstPageFirstSecctionCell_Ht class] forCellWithReuseIdentifier:firstPageFirstSecctionCell_id_Ht];
    [self.collectionView registerClass:[firstPageSecondSecctionCell_Ht class] forCellWithReuseIdentifier:firstPageSecondSecctionCell_id_Ht];
    [self.collectionView registerClass:[FistPageCollectionHeaderView_Ht class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:fistPageCollectionHeaderIdentifier];
#pragma mark 轮播图
    [self setlbView];

    
}
/** 轮播图 */
- (void)setlbView{
    //轮播图
    self.lbView = [[HTLBView alloc] initWithFrame:CGRectMake(0, - 200, kScreenWidth, 200)];
    [self.collectionView addSubview:_lbView];
    _lbView.htLBdelegate = self;
}
/**< 轮播图点击跳转 */
- (void)LBView:(HTLBView *)lbView DidTapTishImageAtIndex:(NSUInteger)index
{//可以跳了
    [self transitionPush];
    WHTWKWebViewVC *webView = [WHTWKWebViewVC new];
    webView.webHtmlUrl = lbView.dataArrayHtml[index - 1];
    [self.navigationController pushViewController:webView animated:YES];
    
}

#pragma mark 集合视图代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (section == 0) {
        
        return self.model.storyDataArray.count;
    }
    
        return self.model.tripDataArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        firstPageFirstSecctionCell_Ht *cell = [collectionView dequeueReusableCellWithReuseIdentifier:firstPageFirstSecctionCell_id_Ht forIndexPath:indexPath];
        //赋值
        cell.model = self.model.storyDataArray[indexPath.row];

        
        return cell;
    }
    firstPageSecondSecctionCell_Ht *cell = [collectionView dequeueReusableCellWithReuseIdentifier:firstPageSecondSecctionCell_id_Ht forIndexPath:indexPath];
    cell.model = self.model.tripDataArray[indexPath.row];
    [cell.avatar_s addTarget:self action:@selector(avatarPushAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    

}
/** 热门游记cell用户头型点击跳转用户详情 */
-(void)avatarPushAction:(UIButton *)sender{
    NSLog(@"可以进行跳转了,跳用户那一个吧");
}

/** 头视图 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        FistPageCollectionHeaderView_Ht *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:fistPageCollectionHeaderIdentifier forIndexPath:indexPath];
        [header.rightButton addTarget:self action:@selector(puchNextPage:) forControlEvents:UIControlEventTouchUpInside];
        if (indexPath.section == 0) {
            header.sectionTitle.text = @"每日精选故事";
            header.rightButton.hidden = NO;
            
        }else{
            header.sectionTitle.text = @"精彩原创和标题";
             header.rightButton.hidden = YES;
        }
        
         return header;
    }
    return nil;
}
/** 第一个分区头视图,右按钮,跳转下一页 */
- (void)puchNextPage:(UIButton *)sender{
    WHTStroryVC *stroryVC = [[WHTStroryVC alloc] init];    
    [self.navigationController pushViewController:stroryVC animated:YES];
}


/** Header大小 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(kScreenWidth, 50);
}

/** 点击方法 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.row);
    //@"http://api.breadtrip.com/v2/new_trip/spot/?spot_id=2387615289"
    if (indexPath.section == 0) {
        WHTFirstPageStoryModel *model = self.model.storyDataArray[indexPath.row];
        WHTStroryDetailVC *storyDetailVC = [WHTStroryDetailVC new];
        storyDetailVC.spot_id = model.spot_id;
        [self.navigationController pushViewController:storyDetailVC animated:YES];
    }
}




#pragma mark FlowLayoutDelegate

/** 每个分区item的大小 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        return  CGSizeMake(([UIScreen mainScreen].bounds.size.width - 30) / 2, ([UIScreen mainScreen].bounds.size.width - 30) / 2 + 30);
        
    }else{
        return CGSizeMake([UIScreen mainScreen].bounds.size.width- 20, 180);
    }
}

#pragma mark- 搜索页
- (void)setSearchPage{
    self.searchPage = [[FirstPageSearchPage_Ht alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.01)];
    [self.view addSubview:self.searchPage];
    self.searchPage.delegate_SearchPage_Ht = self;
    
    
//    //观察者,观察搜索页fram得变化,右按钮作出相应改变咯
   [self.searchPage addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    //ScrollVieww 滚动, 键盘消失掉
    self.searchPage.collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

}

/** 若,SearchPage Frame 变, 那么 右按钮作出相应策应*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
  
//    if ([keyPath isEqualToString:@"frame"]) {
    
        if (self.searchPage.height == kScreenHeight - 64) {
              NSLog(@"aaaaa");
            [self.navigationItem.rightBarButtonItem setTitle:@"取消"];
        }else{
             NSLog(@"xxxxxxx");
            [self.navigationItem.rightBarButtonItem setTitle:@"附近"];
        }
}
#pragma mark 搜索页cell点击跳转
- (void)FirstPageSearchPage_Ht_CellDidSelectedAction:(FirstPageSearchPage_Ht *)FirstPageSearchPage_Ht Category:(NSString *)category WHTFirstPageSearchModel:(WHTFirstPageSearchModel *)model{

}

#pragma mark textFile开始编辑展示搜索页

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    self.searchPage.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
}
#pragma mark textFile将要返回
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    [UIView animateWithDuration:0.3 animations:^{
      self.searchPage.frame = CGRectMake(0, 0, kScreenWidth, 0.01);
    }];
    return YES;
}

- (void)dealloc{
    [self.searchPage removeObserver:self forKeyPath:@"frame" context:nil];
}
@end
